package edu.xpu.compute.recommend.restful;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import edu.xpu.compute.recommend.common.model.PageModel;
import edu.xpu.compute.recommend.common.model.RequestListParam;
import edu.xpu.compute.recommend.common.model.ResponseParam;
import edu.xpu.compute.recommend.entity.SysBook;
import edu.xpu.compute.recommend.entity.user.UserBorrow;
import edu.xpu.compute.recommend.service.SysBookService;
import edu.xpu.compute.recommend.service.user.UserBorrowService;
import edu.xpu.compute.recommend.vo.SysBookExcelVo;

@RestController
@RequestMapping(value="restful/book")
public class SysBookRestful {
	@Autowired
	private SysBookService bookService;
	@Value("${recommend.upload.images.book}")
	private String bookImagePath;
	@Autowired
	private UserBorrowService borrowService;
	
	public static void main(String[] args) {
		String ids = "91-11-11212";
		String replace = ids.replace("-", "");
		System.out.println(replace);
	}
	
	/**
	 * 导入图书信息
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@PostMapping(value="importExcel")
	public ResponseParam<?> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
		InputStream inputStream = file.getInputStream();
		ImportParams importParams = new ImportParams();
		try {
			List<SysBookExcelVo> importExcel = ExcelImportUtil.importExcel(inputStream, SysBookExcelVo.class, importParams);
			if (importExcel != null && importExcel.size() != 0) {
				Date currentDate = new Date();
				Long id = 1L;
				Float price = 0.0F;
				for (SysBookExcelVo sysBookExcelVo : importExcel) {
					price = 0.0F; id = Long.MAX_VALUE;
					String bookBarcodeNumber = sysBookExcelVo.getBookBarcodeNumber();
					/*
					 * 使用ISBN号进行处理，作为id使用
					 */
					String isbnNumber = sysBookExcelVo.getIsbnNumber();
					if (StringUtils.isNotBlank(isbnNumber)) {
						if (isbnNumber.contains(",")) {
							String[] tmpIsbnNumberArr = isbnNumber.split(",");
							String tmpIsbnNumber = tmpIsbnNumberArr[0];
							if (StringUtils.isNotBlank(tmpIsbnNumber)) {
								/*
								 * 看是否包含X， 如果有X，则替换为99
								 */
								if (tmpIsbnNumber.contains("X")) {
									tmpIsbnNumber = tmpIsbnNumber.replace("X", "99");
								}
								try {
									id = Long.parseLong(tmpIsbnNumber.replace("-", ""));
								} catch (Exception e) {}
							} 
						} else {
							if (isbnNumber.contains("X")) {
								isbnNumber = isbnNumber.replace("X", "99");
							}
							try {
								id = Long.parseLong(isbnNumber.replace("-", ""));
							} catch (Exception e) {}
						}
					}
					try {
						id = Long.parseLong(bookBarcodeNumber);
					} catch (Exception e) {}
					String price2 = sysBookExcelVo.getPrice();
					try {
						price = Float.parseFloat(price2);
					} catch (Exception e) {}
					SysBook sysBook = new SysBook(id, sysBookExcelVo.getName(), bookBarcodeNumber, sysBookExcelVo.getLibraryAddr(),
							sysBookExcelVo.getAuthor(), sysBookExcelVo.getPublishingHouse(), price,
							sysBookExcelVo.getCallNumber(), isbnNumber, currentDate);
					try {
						bookService.save(sysBook);
					} catch (Exception e) {}
					/*
					 * 存储借阅信息
					 */
					UserBorrow userBorrow = new UserBorrow(Long.parseLong(sysBookExcelVo.getUserGuid()), sysBookExcelVo.getUserName(),
							id, sysBookExcelVo.getName(), sysBookExcelVo.getBorrowDate());
					userBorrow.setReturnBookDate(sysBookExcelVo.getReturnBookDate());
					try {
						borrowService.save(userBorrow);
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseParam<>(e.getMessage(), 500);
		}
		return new ResponseParam<>("上传成功", 200);
	}
	
	@GetMapping(value="findAll")
	public ResponseParam<List<SysBook>> findAll() {
		List<SysBook> findAll = bookService.findAll();
		return new ResponseParam<List<SysBook>>("数据获取成功", 200, findAll);
	}
	
	@RequestMapping("downloadBookImage/{id}")
	public void downloadBookImage(@PathVariable("id") Long id, HttpServletResponse response) throws Exception {
		SysBook sysBook = bookService.get(id);
		if (sysBook == null) {
			return;
		}
		if (StringUtils.isBlank(sysBook.getCoverImagePath())) {
			return;
		}
		File file = new File(sysBook.getCoverImagePath());
		FileInputStream fis = new FileInputStream(file);
		response.setContentType("application/force-download");
		response.addHeader("Content-disposition", "attachment;fileName=" + sysBook.getOriginalFilename());
		OutputStream os = response.getOutputStream();
		IOUtils.copy(fis, os);
		fis.close();
	}
	
	/**
	 * 上传图书图片
	 * @param multipartFile
	 */
	@PostMapping(value="uploadBookImage/{id}")
	public ResponseParam<String> uploadBookImage(@PathVariable(value="id") Long id, @RequestParam("file") MultipartFile multipartFile) {
		String originalFilename = multipartFile.getOriginalFilename();
		String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
		String newFileName = UUID.randomUUID() + suffixName;
		SysBook sysBook = bookService.get(id);
		if (sysBook == null) {
			return new ResponseParam<String>("为查询到指定的图书!", 200);
		}
		try {
			File dir = new File(bookImagePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			multipartFile.transferTo(new File(bookImagePath+"/"+newFileName));
		} catch (Exception e) {
			return new ResponseParam<String>("文件上传出错！", 500);
		}
		sysBook.setCoverImagePath(bookImagePath+"/"+newFileName);
		sysBook.setOriginalFilename(originalFilename);
		sysBook.setSuffixName(suffixName);
		bookService.save(sysBook);
		return new ResponseParam<String>("上传成功!", 200);
	}

	/**
	 * 获取分页列表信息
	 * @param requestListParam
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@PostMapping(value="list")
	public ResponseParam<PageModel<SysBook>> list(@RequestBody(required=false) RequestListParam<SysBook> requestListParam) {
		if (requestListParam == null) {
			requestListParam = new RequestListParam<>();
		}
		PageModel<SysBook> pageByConditions = bookService.getPageByConditions(requestListParam.getNumber()
													,requestListParam.getSize()
													,requestListParam.getEntity()
													,requestListParam.getSortField()
													,requestListParam.getSortType());
		return new ResponseParam<PageModel<SysBook>>("数据获取成功", 200, pageByConditions);
	}
	/**
	 * 根据id获取数据
	 * @param id
	 * @return
	 */
	@GetMapping(value="get/{id}")
	public ResponseParam<SysBook> get(@PathVariable(value="id") Long id) {
		SysBook sysBook = bookService.get(id);
		return new ResponseParam<SysBook>("数据获取成功", 200, sysBook);
	}
	/**
	 * 保存数据
	 * @param sysBook
	 * @return
	 */
	@PostMapping(value="save")
	public ResponseParam<SysBook> save(@RequestBody SysBook sysBook) {
		sysBook.setCreateDate(new Date());
		SysBook book = bookService.save(sysBook);
		return new ResponseParam<SysBook>("数据保存成功", 200, book);
	}
	/**
	 * 更新数据
	 * @param sysBook
	 * @return
	 */
	@PostMapping(value="update")
	public ResponseParam<SysBook> update(@RequestBody SysBook sysBook) {
		if (sysBook == null || sysBook.getId() != 0L) {
			return new ResponseParam<>("待更新数据没有主键", 500);
		}
		SysBook book = bookService.save(sysBook);
		return new ResponseParam<SysBook>("数据更新成功", 200, book);
	}
	/**
	 * 删除数据
	 * @param id
	 * @return
	 */
	@GetMapping(value="delete")
	public ResponseParam<String> delete(@RequestParam("ids") String ids) {
		try {
			String[] split = ids.split(",");
			for (String idStr : split) {
				bookService.deleteById(Long.parseLong(idStr));
			}
		} catch (Exception e) {
			return new ResponseParam<String>(e.getMessage(), 500);
		}
		return new ResponseParam<String>("数据删除成功", 200);
	}
}
